#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdbool.h>

#define min(a,b) ((a) <= (b) ? (a) : (b))

int main()
{
    const char* host = "192.168.1.250";
    const char* portStr = "9999";

    struct addrinfo hints;
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICSERV;

    struct addrinfo* result;
    getaddrinfo(host, portStr, &hints, &result);

    int cfd = 0;
    struct addrinfo* rp;
    for (rp = result; rp != NULL; rp = rp->ai_next)
    {
        cfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (cfd == -1)
            continue;

        if (connect(cfd, rp->ai_addr, rp->ai_addrlen) != -1)
        {
            printf("connect successed\n");
            break;
        }

        printf("connect failed\n");
        close(cfd);
    }
    freeaddrinfo(result);

    // write(cfd, "123", 3);
    // sleep(5);
    ssize_t hadRead = 0;
    ssize_t lastRead = 0;
    ssize_t totalRead = 1024 * 1024;
    while (hadRead < totalRead)
    {
        char buffer[1025];
        ssize_t readSize = read(cfd, buffer, min(1024, totalRead - hadRead));
        if (readSize <= 0)
        {
            printf("read return %zd, errno: %d\n", readSize, errno);
            sleep(1);
        }
        else
        {
            hadRead += readSize;
            buffer[0] = 0;  // 暂时不打印内容了
            printf("read +%zd, %zd - %zd\n", hadRead - lastRead, lastRead, hadRead);
            lastRead = hadRead;
        }

        usleep(1000 * 50);
    }

    close(cfd);
    return 0;
}
